#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

static int fd,tfd; //fd是串口，afd是am2320

int init_lcd(void);
int read_am2320(float *);
double read_time()
{
  char buf[128];
  int i,ret;
  tfd=open("/proc/uptime",O_RDWR);
  if(tfd<0)perror("time file erroe");
  ret=read(tfd,buf,sizeof(buf)); 
  if (ret<=0) return 0;
  for(i=0;!buf[i] || buf[i]!='.';i++);
  buf[i]='\0';
  close(tfd);
  return atof(buf); 
}

int main(void)
{
  char openls_logo[]="DS16(3,3,'www.openloongson.org',6);";
  char zz[]="DS16(3,22,'Power by zz',6);";
  char email[]="DS16(3,41,'Email:90807@QQ.COM',6);";
  char temper[64];
  char rh[64]; 
  char uptime[64]; 
  float data[2];
  double rtime;
  init_lcd();
  read_am2320(data);
  printf("ZZ: AM2320 RH:%.1f | temper: %.1f Power by zz!\n",data[0],data[1]);    
  printf("Email: 90807@QQ.COM\n");    

  while(1)
  { 
  rtime=read_time();
  read_am2320(data);
  write(fd,"BOXF(1,1,218,79,5);",19);
  write(fd,"BOX(0,0,219,80,1);",18);
  write(fd,"SBC(5);",7);
  write(fd,openls_logo,sizeof(openls_logo)-1);
  write(fd,zz,sizeof(zz)-1);
  write(fd,email,sizeof(email)-1);


  write(fd,"SBC(3);",7);
  sprintf(temper,"DS16(3,83,'Temper: %.1f',4);",data[1]);
  sprintf(rh,"DS16(3,102,'RH: %.1f%',4);",data[0]);
  sprintf(uptime,"DS16(3,121,'Sys time: %.0lfs',4);",rtime);
  write(fd,temper,strlen(temper));
  write(fd,rh,strlen(rh));
  write(fd,uptime,strlen(uptime));
  write(fd,"\r\n",2);
  usleep(600*1000);
 }
}

int read_am2320(float *data)
{
  int i2c_fd;
  char buf[4];

  i2c_fd=open("/dev/AM2320",O_RDWR);
  if(i2c_fd<0)perror("ZZ: OPEN AM2320 ERROR");
  read(i2c_fd,buf,4);
  data[0]=((buf[0]<<8)+buf[1]);
  data[0]=data[0]/10.00;
  data[1]=((buf[2]<<8)+buf[3]);
  data[1]=data[1]/10.00;
  close(i2c_fd);
 return 0;
}

int init_lcd(void)
{
  struct termios newt,oldt;
  char cls[]="CLS(3);\x0d\x0a";
  fd=open("/dev/ttyS1",O_RDWR|O_NOCTTY|O_NDELAY);
  if(fd<0)
  {
   perror("open com");
  }

  if(tcgetattr(fd,&oldt))
  {
   perror("save com setup");
  }

  newt.c_cflag |= CLOCAL|CREAD;
  newt.c_cflag &=~CSIZE;
  newt.c_cflag |=CS8;  // 8位
  newt.c_cflag &=~PARENB; //无校检 N
  newt.c_cflag &=~CSTOPB; //停止位 1
  cfsetispeed(&newt,B115200); //波特率9600
  cfsetospeed(&newt,B115200);
  newt.c_cc[VTIME]=0;
  newt.c_cc[VMIN]=0;
  tcflush(fd,TCIFLUSH);
  if(tcsetattr(fd,TCSANOW,&newt)!=0)
  {
    perror("com set error");
  }
  write(fd,cls,sizeof(cls));
  printf("lcd set done!\n");
return 0;
}
